from flask import Blueprint, request, jsonify, send_file
from database import TaskDAO, UploadDAO
from task_manager import TaskManager, BatchTaskManager
from config import Config
import os
from utils.logger import get_logger

logger = get_logger(__name__)


def create_task_routes(task_dao: TaskDAO, upload_dao: UploadDAO, task_manager: TaskManager):
    """创建任务相关路由"""

    task_bp = Blueprint('task', __name__)
    batch_manager = BatchTaskManager(task_manager)

    @task_bp.route('/process-video', methods=['POST'])
    def process_video():
        """处理视频背景替换请求"""
        try:
            # 解析参数
            params = {
                'canvas_width': int(request.form.get('canvas_width', Config.DEFAULT_CANVAS_WIDTH)),
                'canvas_height': int(request.form.get('canvas_height', Config.DEFAULT_CANVAS_HEIGHT)),
                'video_scale': float(request.form.get('video_scale', 1.0)),
                'video_x': int(request.form.get('video_x', 0)),
                'video_y': int(request.form.get('video_y', 0)),
                'bg_scale': float(request.form.get('bg_scale', 1.0)),
                'bg_x': int(request.form.get('bg_x', 0)),
                'bg_y': int(request.form.get('bg_y', 0)),
                'keep_human_ratio': request.form.get('keep_human_ratio', 'false').lower() == 'true',
                'keep_bg_ratio': request.form.get('keep_bg_ratio', 'false').lower() == 'true',
                'output_format': request.form.get('output_format', Config.DEFAULT_OUTPUT_FORMAT)
            }

            # 添加日志输出参数
            # logger.info(f"处理视频请求参数: {params}")


            human_file_id = request.form.get('human_file_id')
            background_file_id = request.form.get('background_file_id')
            output_name = request.form.get('output_name', 'output_video.mp4')

            if not human_file_id or not background_file_id:
                return jsonify({'success': False, 'message': '缺少文件ID'})

            # 验证文件存在
            human_upload = upload_dao.get_upload_by_id(human_file_id)
            bg_upload = upload_dao.get_upload_by_id(background_file_id)

            if not human_upload or not bg_upload:
                return jsonify({'success': False, 'message': '文件不存在'})

            # 创建任务
            task_id = task_manager.create_task(human_file_id, background_file_id, params, output_name)

            if not task_id:
                return jsonify({'success': False, 'message': '创建任务失败'})

            # 生成输出路径
            output_filename = f"{task_id}_{output_name}"
            output_path = os.path.join(Config.OUTPUT_FOLDER, output_filename)

            # 开始处理
            task_manager.start_processing(
                task_id, human_upload['file_path'], bg_upload['file_path'],
                output_path, params
            )

            return jsonify({
                'success': True,
                'task_id': task_id,
                'message': '任务已开始处理'
            })

        except Exception as e:
            logger.error(f"处理视频请求失败: {e}")
            return jsonify({'success': False, 'message': f'服务器错误: {str(e)}'})

    @task_bp.route('/batch-process', methods=['POST'])
    def batch_process():
        """批量处理视频"""
        try:
            data = request.get_json()
            combinations = data.get('combinations', [])
            params_raw = data.get('params', {})

            # 确保参数类型正确
            params = {
                'canvas_width': int(params_raw.get('canvas_width', Config.DEFAULT_CANVAS_WIDTH)),
                'canvas_height': int(params_raw.get('canvas_height', Config.DEFAULT_CANVAS_HEIGHT)),
                'video_scale': float(params_raw.get('video_scale', 1.0)),
                'video_x': int(params_raw.get('video_x', 0)),
                'video_y': int(params_raw.get('video_y', 0)),
                'bg_scale': float(params_raw.get('bg_scale', 1.0)),
                'bg_x': int(params_raw.get('bg_x', 0)),
                'bg_y': int(params_raw.get('bg_y', 0)),
                'keep_human_ratio': bool(params_raw.get('keep_human_ratio', False)),
                'keep_bg_ratio': bool(params_raw.get('keep_bg_ratio', False)),
                'output_format': params_raw.get('output_format', Config.DEFAULT_OUTPUT_FORMAT)
            }

            # 添加日志输出参数
            # logger.info(f"批量处理参数: {params}")

            if not combinations:
                return jsonify({'success': False, 'message': '没有组合需要处理'})

            # 创建批量任务
            batch_id, task_ids = batch_manager.create_batch_task(combinations, params)

            if not batch_id:
                return jsonify({'success': False, 'message': '创建批量任务失败'})

            # 开始批量处理
            success = batch_manager.start_batch_processing(batch_id, upload_dao)

            if success:
                return jsonify({
                    'success': True,
                    'batch_id': batch_id,
                    'task_ids': task_ids,
                    'message': f'已提交 {len(task_ids)} 个处理任务'
                })
            else:
                return jsonify({'success': False, 'message': '启动批量处理失败'})

        except Exception as e:
            logger.error(f"批量处理失败: {e}")
            return jsonify({'success': False, 'message': '批量处理失败'}), 500

    @task_bp.route('/task-status/<task_id>', methods=['GET'])
    def get_task_status(task_id):
        """获取任务状态"""
        task_status = task_manager.get_task_status(task_id)

        if not task_status:
            return jsonify({'error': '任务不存在'}), 404

        return jsonify(task_status)

    @task_bp.route('/batch-status/<batch_id>', methods=['GET'])
    def get_batch_status(batch_id):
        """获取批量任务状态"""
        batch_status = batch_manager.get_batch_status(batch_id)

        if not batch_status:
            return jsonify({'error': '批量任务不存在'}), 404

        return jsonify(batch_status)

    @task_bp.route('/download/<filename>', methods=['GET'])
    def download_file(filename):
        """下载处理完成的视频文件"""
        file_path = os.path.join(Config.OUTPUT_FOLDER, filename)
        if not os.path.exists(file_path):
            return jsonify({'error': '文件不存在'}), 404

        return send_file(file_path, as_attachment=True)

    @task_bp.route('/task-preview/<task_id>')
    def get_task_preview(task_id):
        """获取任务预览图"""
        try:
            task = task_dao.get_task_by_id(task_id)

            if task and task['preview_path'] and os.path.exists(task['preview_path']):
                return send_file(task['preview_path'])
            else:
                return jsonify({'error': '预览图不存在'}), 404

        except Exception as e:
            logger.error(f"获取任务预览失败: {e}")
            return jsonify({'error': '获取预览失败'}), 500

    return task_bp